<?php
 
 class NewsAction extends AdminPublicAction {
	
/** =============
	列表
=================**/	
    public function index()
	{	
		if((isset($_GET['sort'] ) && !empty($_GET['sort'])) && (isset($_GET['updown'] ) && !empty($_GET['updown']))){
			 $sort   = I('sort');
			 $upDown = I('updown');
		}else{
			 $_GET['sort'] = $sort = "sort_order";
			 $_GET['updown'] = $upDown = "desc";
			
		}
		$keyword = I('keyword','');
		
		if(tep_not_null($keyword))$where['news_title']  = array('like','%'.$keyword.'%');
		$where['news_language_id'] = (int)L('lan_id');
		
		import("ORG.Util.Page");
		$page = 10;	
		$count = D('IndexView')->where($where)->count();	
		$Page = new Page($count, $page);		
		$list   = D('IndexView')->getAll($where,$Page->firstRow. ',' . $Page->listRows,$sort.' '.$upDown);		
		$show = $Page->show();	

			
		if (S("success") != "")
		{
			$this->assign("msg", '<div class="success">'.S("success").'</div>');
			S('success',NULL);
		}
		if (S("err") != "")
		{
			$this->assign("msg", '<div class="err">'.S("err").'</div>');
			S('err',NULL);
		}
		$this->keyword = $keyword;
		$this->listing = $list;
		$this->page = $show;
		$this->left_news = 'current';
		$this->display();			
		
    }
/** =============
	添加 & 編輯
=================**/	
	public function  detail(){
		
		$editId = I('id','',intval);
		
		$langList = explode(",", C('LANG_LIST'));
		
		$lang = array();
		foreach($langList as $item)
		{
			$langTxt = '';
			if ($item == 'tchinese') $langTxt = '繁體';
			if ($item == 'schinese') $langTxt = '简体';
			if ($item == 'english')  $langTxt = 'English';
			$lang[] = array("value" => $item, 'txt'=> $langTxt );			
		}
		
	
		
		
		
		if(tep_not_null($editId)&&is_numeric($editId)){
			/*編輯*/
			$list   = D('IndexView')->getOne(array('ni.news_language_id' => (int)L('lan_id'),'n.news_id' =>$editId));	
			$newsToLang = D('IndexView')->getAll(array('n.news_id' =>$editId)); //獲取多語言信息.
			
			foreach ($newsToLang as $value)
			{				
				$titleArr[$value['news_language_id']]   =   $value['news_title'];
				$descArr[$value['news_language_id']]    =   $value['news_description'];
				$iDescArr[$value['news_language_id']]   =   $value['image_description'];
			}	
				
			if ( isset($list["news_image"]) && $list["news_image"] != '')
			{
				$imageShow = '<input type="hidden"  name="del_iamge" value="flase" />
							  <div id="image">
							   <a  href="'.__ROOT__.'/Public/images/news/thumb/m_'.$list["news_image"].'" class="fancyBox"><img src="'.__ROOT__.'/Public/images/news/thumb/m_'.$list["news_image"].'" width="200"></a><br />
							   <a  href="#" onclick="delImages();return false;"  class="del">Delete</a></div>';
			}	
			
			
			$this->titleArr = $titleArr;			  
			$this->descArr = $descArr;
			$this->iDescArr = $iDescArr;				  
			$this->listInfo = $list;
			$this->imageShow = $imageShow;	
			$this->editId = $editId;
			$this->addDate = $list['news_added'];
			$this->action = 'editHandle';
			$this->actionName = 'Save';
		}else{
		//*添加*/
			$this->addDate = date('Y-m-d');
			$this->action = 'addHandle';
			$this->actionName = 'Add';
		}
		$this->lang = $lang;
		$this->left_news = 'current';
		$this->langList = $langList;
		$this->display();	
		
	} 
/** =============
	添加处理
=================**/
	
	public function addHandle()
	{	
		if(IS_POST){
			if(tep_not_null(I('post.news_added'))){
				$data['news_added'] = date("Y-m-d",strtotime(I('post.news_added')));
			}else{
				$data['news_added'] = date("Y-m-d");
			} 
			$data['news_status'] = I('post.news_status');
			$data['top_flag'] = I('post.top_flag');
			$data['sort_order'] = I('post.sort_order');
			$news = M("news");
			$insertId = $news->add($data);		
			
			
			
			$language = explode(",", C('LANG_LIST'));
			$i = 0;
			$map = array();
			foreach( $language as $item)
			{
				$i++;
				$map['news_id'] = $insertId;
				$map['news_language_id'] = $i;
				$map['news_title'] = I('post.news_title_'.$i);
				$map['news_description'] = tep_db_prepare_input(I('post.news_description_'.$i));
				$map['image_description'] = I('post.image_description_'.$i);
				$newsDesc = M("news_info");
				$newsDesc->add($map);
			}	
			
			if ($_FILES['news_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('news_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/news/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/news/thumb/';
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());				
					$this->redirect('index');
				}
				else
				{
					$info =  $upload->getUploadFileInfo();
					$news = M("news")->where(array("news_id" => $insertId))->setField('news_image',$info[0]['savename']);	
					S('success','News successfully added!');			
					$this->redirect('index');			
				}	
			}else{
				 	S('success','News successfully added!');			
					$this->redirect('index');	
			}
		}else{
			$this->redirect('index');	
		}
	}
/** =============
	编辑处理
=================**/	
	public function editHandle()
	{
		if(IS_POST){
			
			$id = I('post.editId');
			$data['news_id'] = $id;
			$data['sort_order'] = I('post.sort_order');
			$data['news_modification'] = date("Y-m-d H:i:s");
			if(tep_not_null(I('post.news_added'))){
				$data['news_added'] = date("Y-m-d",strtotime(I('post.news_added')));
			}else{
				$data['news_added'] = date("Y-m-d");
			} 
			$data['news_status'] = I('post.news_status');
			$data['top_flag'] = I('post.top_flag');
			M("news")->save($data);		
			

			$language = explode(",", C('LANG_LIST'));
			$i = 0;
			$map = array();
			foreach( $language as $item)
			{
				$i++;		
				$map['news_title'] = I('post.news_title_'.$i);
				$map['news_description'] = tep_db_prepare_input(I('post.news_description_'.$i));
				$map['image_description'] = I('post.image_description_'.$i);
				$newsDesc = M("news_info");
				$newsDesc->where(array('news_id'=> $id,'news_language_id' => $i))->save($map);
			}
			
			
			if ($_FILES['news_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('news_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/news/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/news/thumb/';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());
					$this->redirect('index');
				}
				else
				{
					$image = M("news")->where(array("news_id" => $id))->getField('news_image');
					@unlink("./Public/images/news/".$image);
					@unlink("./Public/images/news/thumb/s_".$image);
					@unlink("./Public/images/news/thumb/m_".$image);
					$info =  $upload->getUploadFileInfo();
					$news = M("news")->where(array("news_id" => $id))->setField('news_image',$info[0]['savename']);	
				}
			}
			else
			{
				if (isset($_POST['del_iamge']) && $_POST['del_iamge'] == 'true')
				{
					$image = M("news")->where(array("news_id" => $id))->getField('news_image');
					@unlink("./Public/images/news/".$image);
					@unlink("./Public/images/news/thumb/s_".$image);
					@unlink("./Public/images/news/thumb/m_".$image);
					M("news")->where(array('news_id' => $id))->setField('news_image','');
				}
			}	
			S('success','News update successfully!');
			$this->redirect('index');
		}else{
			$this->redirect('index');
		}
	}
	
	public function delete()
	{
		$id  = I('id');
		if(tep_not_null($id) && is_numeric($id)){	
			$image = M("news")->where(array("news_id" => $id))->getField('news_image');
			@unlink("./Public/images/news/".$image);
			@unlink("./Public/images/news/thumb/s_".$image);
			@unlink("./Public/images/news/thumb/m_".$image);
			M('news')->where(array('news_id' => $id))->delete();  
			M('news_info')->where(array('news_id' => $id))->delete();  
			S('success','News deleted successfully!');
			$this->redirect('index');
		}else{
			S('err','News deleted failure!');
			$this->redirect('index');
			}
	}
	
	public function changeStatus(){			
		$check = M("news")->where(array("news_id" => (int)$_GET['id']))->getField('news_status');	
	    $news_status = ($check == 1)?0:1;		
		M("news")->where(array("news_id" => (int)$_GET['id']))->setField('news_status',$news_status);
		echo (int)$news_status;		
			
	}
	
	
	
	
}